// pages/aftersale/applyforsale.js
import Router from '../../utils/router.js';
import base from '../../config/base.js';
import service from '../../services/aftersale';
import util from '../../utils/util.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addimg_icon: base.static + 'aftersale/add-icon1.png',
    service_arrowimg: base.static + 'aftersale/GroupCopy.png',
    choose_img: base.static + 'aftersale/contai.png',
    close_img: base.static + 'aftersale/delete.png',
    reasonarr: [],//退货原因
    value: '点击选择',
    textarea_str: '',
    list: [],//图片地址数组
    img_flag: true,
    order: '',
    filepath: [],//oos图片地址数组
    saleafter_type: '',//退货类型
    img_flagbloon: true,//上传图片节流
    maxlength: '',
    tuimuch:'',
    telvalue:'',
    total_group:'',
  },
  //点击选择事件
  bindPickerChange: function (e) {
    let that = this;
    let reason = that.data.reasonarr;
    that.setData({
      value: reason[e.detail.value].reason,
      value_id: reason[e.detail.value].reason_id
    })
  },
  //问题描述文本域
  EventHandle(e){
   let textarea_str = e.detail.value;
    this.setData({
      textarea_str: textarea_str
    })
  },
  //退款金额
  inputeventHandle(e){
    let val = e.detail.value;
    this.setData({
      tuimuch: val
    })
    if (val.indexOf('.') != -1) {
      if (val.split('.')[1].length > 2) {
        let num = this.data.order.total_money.split('.')[0].length;
        this.setData({
          maxlength: num + 3
        })
      }
    } else if (val.indexOf('.') == 1) {
      console.log(111)
      let num = this.data.order.total_money.split('.')[0].length;
      this.setData({
        maxlength: num + 3
      })
    }
    if (val.length == 0) {
      console.log(111)
      wx.showToast({
        title: '退款金额不能为空',
        icon: 'none'
      })
      return;
    }
    let rex = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
    if (isNaN(val) || val.indexOf('.') == 0 || !rex.test(val)){
      wx.showToast({
        title: '请输入正确退款金额',
        icon:'none'
      })
    }
    if (Number(val) > Number(this.data.total_group)){
      wx.showToast({
        title: '不能超过最大金额',
        icon: 'none'
      })
    }
  },
  //联系电话
  telhandle(e) {
    let val = e.detail.value;
    this.setData({
      telvalue: val
    })
    let rex1 = /^1[3456789]\d{9}$/;
    if (!rex1.test(val)) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none'
      })
    }
  },
  //选择图片
  chooseImage(){
    let that = this;
    wx.chooseImage({
      count: 1, // 最多上传1张
      success: function (res) {
        let tempFilePaths = res.tempFilePaths;
         //上传图片到oos
        let auth_token = wx.getStorageSync('auth_token');
        let apiUrl = base.apiUrl;
         wx.uploadFile({
           url: apiUrl + '/uploadImg',
           filePath: tempFilePaths[0],
           name: 'file',
           header: {
             'Authorization': `Bearer ${auth_token}`
           },
           success: function(res){
             console.log(res)
             let filepath = that.data.filepath;
             let url = JSON.parse(res.data).data.url;//处理反/问题
             filepath.push(url);
             that.setData({
                filepath: filepath,
                img_flagbloon: true
            })
           }
         })
        let arr = that.data.list.concat(tempFilePaths)
          that.setData({
            list:arr
          })
        //如果图片等于三张隐藏上传图片按钮
        if (that.data.list.length == 3) {
          that.setData({
            img_flag : false
          })
        }
      }
    })
  },
  //预览图片
  previewImage(e){
    let that = this;
    let url = e.currentTarget.dataset.src;
    let tempFilePaths = that.data.filepath;
    let arr = []
    for (let i=0; i<tempFilePaths.length;i++){
      arr[i] = 'https:' + tempFilePaths[i];
    }
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },
  //删除照片
  closeimage(e){
    let index = e.currentTarget.dataset.index;
    let list = this.data.list;
    let filepath = this.data.filepath;
    list.splice(index, 1);
    filepath.splice(index, 1);
    this.setData({
      list: list,
      filepath: filepath
    })
     //如果图片小于三张显示上传图片按钮
    if(list.length < 3){
      this.setData({
        img_flag: true
      })
    }
  },
  //提交申请售后信息
  createmsg(){
    let that = this;
    let params = {
      orid: that.data.orid
    }
    service.submission(params,function(res){
      if(res && res.code == 1){
        let data = res.data.order;
        let maxlength = data.total_money.split('.')[0].length + 3;
        let total_group = '';
        let tuimuch = '';
        if (data.solitaire_money == 0){//正常订单
          if (data.balance > 0) {
            tuimuch = util.toDecimal2(util.floatAccMul((data.total_money), 1) + util.floatAccMul((data.balance), 1));
          } else {
            tuimuch = data.total_money;
          }
        }else {//群接龙订单
          let chajia = data.solitaire_money * data.goods_num;
          tuimuch = util.toDecimal2(util.floatAccMul(chajia, 1));
        }
        that.setData({
          order: data,
          maxlength: maxlength,
          telvalue: data.tel,
          tuimuch: tuimuch,
          reasonarr: res.data.reason,//退货原因
          total_group: tuimuch,
        })
      }
    })
  },
  //提交申请售后
  submit(){
    let that = this;
    if (that.data.value == '点击选择') {
      wx.showToast({
        title: '请填写退款原因',
        icon: 'none'
      })
      return;
    }
    //如果图片 没有上传成功做节流
    if (!that.data.img_flagbloon) {
      wx.showToast({
        title: '正在上传图片',
        icon: 'none'
      })
      return;
    }
    //验证退款金额
    let rex = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
    let val = that.data.tuimuch;
    if (that.data.tuimuch == '') {
      wx.showToast({
        title: '退款金额不能为空',
        icon: 'none'
      })
      return;
    }
    if (isNaN(val) || !rex.test(val)) {
      wx.showToast({
        title: '请输入正确退款金额',
        icon: 'none'
      })    
      return;
    }
   
    if (that.data.tuimuch > Number(that.data.total_group)) {
      wx.showToast({
        title: '退款金额不能超过最大金额',
        icon: 'none'
      })          
      return;
    }
    let rex1 = /^1[34578]\d{9}$/;
    if (!rex1.test(that.data.telvalue)) {
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none'
      })                 
      return;
    }
    if (that.data.textarea_str.length <= 0){
      wx.showToast({
        title: '请填写问题描述',
        icon: 'none'
      })
      return;
    }
    if (that.data.filepath.length <= 0){
      wx.showToast({
        title: '请上传凭证',
        icon: 'none'
      })
      return;
    }
    // 改变图片格式
    let arr = that.data.filepath;
    let obj = {};
    let newarr = [];
    for (var i = 0; i < arr.length;i++){
      let obj = {url: arr[i]}
      newarr[i] = obj;
    }
    let param = {
      orid: that.data.orid,
      reason_id: that.data.value_id,
      refunds: that.data.tuimuch,
      tel: Number(that.data.telvalue),
      customer_msg: that.data.textarea_str,
      saleafter_type: that.data.saleafter_type,
      saleafter_evidence: newarr
    }
    //提交申请售后
    service.saleAfterCreate(param,function(res){
      if(res && res.code == 1){
        let srorid = res.data.srorid;
        let orid = that.data.orid;
        Router.go('afterdetail', `srorid=${srorid}&orid=${orid}`)
      }
      else if (res && res.code == 4111){
         wx.showToast({
           title: '售后单已存在',
           icon: 'none'
         })
      } 
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orid: options.orid,
      saleafter_type: options.saleafter_type
    })
    this.createmsg();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
})